package handlers

import (
	"github.com/gin-gonic/gin"
	"novel-world/cache"
	"novel-world/models"
	"novel-world/pkg"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "账户或密码不能为空",
		})
		return
	}
	reds_key := "reds_log_" + username
	logCount, _ := cache.Rdb.Get(cache.Ctx, reds_key).Int()
	if logCount >= 3 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "登录失败3次，禁止登录",
		})
		return
	}
	var user models.User
	err := models.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "账户不存在",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "账户不存在",
		})
		return
	}
	if pkg.Md5(password) != user.Password {
		cache.Rdb.Incr(cache.Ctx, reds_key)
		if logCount == 2 {
			cache.Rdb.Set(cache.Ctx, reds_key, 3, time.Hour*2)
			c.JSON(200, gin.H{

				"code": 400,
				"msg":  "登录已锁定,2小时后解锁",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "登录失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"user": user,
	})

}
